/*******************************************************************************

PooledRegions analysis_travelcost.do

2021.04.16 (DJ) Created

This do file calculates the upper and lower bound travel cost estimates

RQ_rural_cost_USD
MT_mkt_cost_USD

*******************************************************************************/

use "${analysis}/Kilimanjaro rq_census_mt_vt_google.dta", clear
	rename  (district ward village_name market) (survey_district survey_ward survey_village primary_market)
	
	append using "${analysis}/Manyara rq_census_mt_vt_google.dta"
	
	cap drop village_id
	egen village_id = group(survey_region survey_district survey_ward survey_village)

	tempfile master
	save `master'

	
	
/*******************************************************************************
	TRAVEL COSTS on MAJOR ROADS
*******************************************************************************/

// MARKETS TO CITIES
	estimates clear
	use `master', clear
		drop MT_mkt_vil_cost_USD* MT_mkt_vil_hrs *nearcity* *turnoff* 
		keep MT_mkt_*_hrs survey_region primary_market MT_mkt_*_cost_USD* google_mkt_*_km google_mkt_*_hrs
		duplicates drop
		
		reshape long MT_mkt@_hrs MT_mkt@_cost_USD MT_mkt@_cost_USD_3ways google_mkt@_km google_mkt@_hrs, i(primary_market) j(city) string
		drop if city=="_dar"
		
		gen google_mkt_min 	= google_mkt_hrs*60
		gen MT_mkt_min 		= MT_mkt_hrs * 60
		
		foreach dep in MT_mkt_cost_USD{
		
			foreach indep in google_mkt_km {		
		
				eststo: xi: reg `dep' `indep', nocons cluster(primary_market)
				distinct primary_market if e(sample)
				estadd local numM = `r(ndistinct)'
				
				local b 		= _b[`indep']
				local se		= _se[`indep']
				local nclust	= e(N_clust)
					
				local paved_bl = `b' - invt(`nclust'-1, .975)*`se'
				local paved_bu = `b' + invt(`nclust'-1, .975)*`se'
				
				estadd local bl = `paved_bl'
				estadd local bu = `paved_bu'
			}
		}
		
		
	
/*******************************************************************************
	TRAVEL COSTS on RURAL ROADS (VILLAGES TO PRIMARY MARKETS)
*******************************************************************************/	

	use `master', clear
	
	foreach dep in RQ_rural_cost_USD {
	
		foreach indep in google_vil_mkt_km {
	
			eststo: xi: reg `dep' `indep', nocons cluster(village_id)
			distinct village_id if e(sample)
			estadd local numV = `r(ndistinct)'
			
			local b 		= _b[`indep']
			local se		= _se[`indep']
			local nclust	= e(N_clust)
				
			local rural_bl = `b' - invt(`nclust'-1, .975)*`se'
			local rural_bu = `b' + invt(`nclust'-1, .975)*`se'
			
			estadd local bl = `rural_bl'
			estadd local bu = `rural_bu'
			
		}
	}
	
	esttab, se(a1) b(2) se replace compress nogap star(* 0.10 ** 0.05 *** 0.01) sca("N Observations" "numV Villages" "bl Lower Bound" "bu Upper Bound") 
	
	global rural_bl = `rural_bl' 
	global rural_bu = `rural_bu'
	global paved_bl = `paved_bl'
	global paved_bu = `paved_bu'
	
	
	exit
